<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/5/6
 * Time: 16:15
 * Desc: 微信h5支付回调
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\index\service\WeixinService;
use think\Config;

class Notifywxpaymobile extends Controller{
    /**
     * @Author  lingyun
     * @Desc    h5支付订单回调信息
     */
    public function index(){
//        $notifyInfo = $this->get_notify();
//        $notify = '<xml><appid><![CDATA[wxca55ae67ce44cc82]]></appid>
//                    <bank_type><![CDATA[CFT]]></bank_type>
//                    <cash_fee><![CDATA[1]]></cash_fee>
//                    <fee_type><![CDATA[CNY]]></fee_type>
//                    <is_subscribe><![CDATA[Y]]></is_subscribe>
//                    <mch_id><![CDATA[1496012992]]></mch_id>
//                    <nonce_str><![CDATA[7zqEf9hKQ0Qxp3tzXKLj9Wi2caiuYSkR]]></nonce_str>
//                    <openid><![CDATA[ohW9z0y7Ia7iILgB9j2Y_otsIXb8]]></openid>
//                    <out_trade_no><![CDATA[20180506172754899903000001]]></out_trade_no>
//                    <result_code><![CDATA[SUCCESS]]></result_code>
//                    <return_code><![CDATA[SUCCESS]]></return_code>
//                    <sign><![CDATA[0856A22437DE9A2F203057FC7479E558]]></sign>
//                    <time_end><![CDATA[20180506172759]]></time_end>
//                    <total_fee>1</total_fee>
//                    <trade_type><![CDATA[MWEB]]></trade_type>
//                    <transaction_id><![CDATA[4200000122201805064041798493]]></transaction_id>
//                    </xml>';

//        $res = '{"appid":"wxca55ae67ce44cc82","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1496012992","nonce_str":"6YmubYoAAMAkO4IBPaQBAPL8PG1pIwrj","openid":"ohW9z0y7Ia7iILgB9j2Y_otsIXb8","out_trade_no":"20180506192705213900000001","result_code":"SUCCESS","return_code":"SUCCESS","sign":"DFD3BD3520526B30B49BC9DEE98799A0","time_end":"20180506192713","total_fee":"1","trade_type":"MWEB","transaction_id":"4200000124201805064170000920"}';
        $notifyInfo = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($notifyInfo===FALSE){
            // 接口失败的处理
            $this->error('支付失败',url('User/index'),1);
        }else{
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                //订单详情
                $order = Db::name('order')->where("order_sn",$notifyInfo['out_trade_no'])->find();
                //会员信息
                $member = Db::name('user')->where('uid',$order['uid'])->field('uid,openid,addtime')->find();
                //更新订单状态,进行判断防止多次进行数据库操作
                if($order['pay_status'] == 0){
                    //更新订单信息
                    Db::name('order')->where('order_sn',$notifyInfo['out_trade_no'])->update(array('pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time(),'remark'=>'已支付','order_status'=>1));
                    //支付记录
//                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$notifyInfo['out_trade_no'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>2,'pay_sign'=>1,'amount'=>$order['final_amount'],'addtime'=>time(),'remark'=>'支付订单']);
                    //订单动作
                    Db::name('order_action')->insert(['uid'=>$order['uid'],'order_id'=>$order['id'],'action_user'=>0,'order_status'=>1,'pay_status'=>1,'status_desc'=>'已支付，待发货','storeid'=>$order['store_id'],'addtime'=>time()]);

                    //订单详情
                    $order_detail = db('order_details')->where('order_id',$order['id'])->field('id,uid,goods_num,order_id,spec_id,spec_detail,store_goods_stock_id')->select();

                    $ids = implode(',',array_column($order_detail, 'id'));
//                    $store_goods_stock_id = implode(',',array_column($order_detail, 'store_goods_stock_id'));

                    //更新订单详情的支付状态
                    db('order_details')->where('id','in',$ids)->update(['status'=>1]);
                    foreach($order_detail as $k => $v){
                        //更新门店库存
//                        db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->setDec('stock',$v['goods_num']);
                        $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                        $cur_stock = $stock['stock'] - $v['goods_num'];
                        //更新门店库存
                        db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                        $arr = [
                            'goods_id'=>$v['goods_id'],
                            'goods_spec_id'=>$stock['goods_spec_id'],
                            'title'=>$v['spec_detail'],
                            'order_id'=>$order['id'],
                            'store_id'=>$order['store_id'],
                            'types'=>2,
                            'ruku_num'=>0,
                            'tuihuo_num'=>0,
                            'chuku_num'=>$v['goods_num'],
                            'sunhao_num'=>0,
                            'remark'=>$order['order_sn'],
                            'cur_stock'=>$cur_stock,
                            'addtime'=>time(),
                            'order_sn'=>$order['order_sn']
                        ];
                        db('store_goods_log')->insert($arr);

                    }

                    //更新优惠券的使用情况
                    db('user_ycard')->where(['uid'=>$order['uid'],'id'=>$order['coupon_id']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                    //更新代金券的使用情况
                    db('user_ycard')->where(['uid'=>$order['uid'],'id'=>$order['cash_coupon_id']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);

                    $pay_log_arr = [
                        'order_id'=>$order['id'],
                        'order_sn'=>$order['order_sn'],
                        'order_type'=>1,
                        'uid'=>$order['uid'],
                        'pay_type'=>$order['pay_type'],
                        'pay_sign'=>1,
                        'store_id'=>$order['store_id'],
                        'amount'=>$order['final_amount'],
                        'remark'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                        'addtime'=>time()
                    ];
                    db('pay_log')->insert($pay_log_arr);            //新增支付记录

                    //更新门店金额数据
                    $store = db('store')->where('id',$order['store_id'])->find();
                    $update_store_amount_data = [
                        'total_amount'=>$store['total_amount']+$order['final_amount'],
                        'wx_amount'=>$store['wx_amount']+$order['final_amount']
                    ];
                    //更新门店线上支付宝收入
                    db('store')->where('id',$order['store_id'])->update($update_store_amount_data);

                    $store_credit_log = [
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'type' => 1,
                        'credit' => $order['final_amount'],
                        'cur_credit' => $store['total_amount'] + $order['final_amount'],
                        'remark' => '销售商品收入',
                        'addtime' => time(),
                        'order_type' => 1,
                        'order_sn' => $order['order_sn'],
                        'pay_type' => 3
                    ];

                    db('store_credit_log')->insert($store_credit_log);

                    //三级分销赠送会员积分
                    third_tier_distribution($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],0,$order['order_sn']);

                    //存在会员的openid就推送模板消息
                    if(!empty($member['openid'])){
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("mobanid.xiadan")["tempid"],
                            "url" 		  =>config("mobanid.xiadan")["url"],
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>"支付成功",        		"color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$order['order_sn'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>$order['final_amount'], 		"color"=>"#743A3A"],
                                "keyword3"		=>["value"=>"微信支付","color"=>"#743A3A"],
                                "remark"		=>["value"=>"感谢您的购买，请注意查收商品", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }else{
                $this->error('支付失败',url('User/index'),1);
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    h5支付代金券回调
     * 2018-05-05
     */
    public function cash_coupon(){
        $notifyInfo = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($notifyInfo===FALSE){
            // 接口失败的处理
            $this->error('支付失败',url('User/index'),1);
            //echo $pay->errMsg;
            //$json = json_encode($notifyInfo);
        }else{
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                //会员的代金券列表
                $coupon = db('cash_coupon_list')->where('order_sn',$notifyInfo['out_trade_no'])->find();
                if($coupon['pay_status'] != 1){
                    //会员信息
                    $member = db('user')->where('uid',$coupon['uid'])->find();

                    $data_arr = [
                        'id'=>$coupon['id'],
                        'order_code'=>$notifyInfo['transaction_id'],
                        'pay_time'=>time(),
                        'pay_status'=>1,
                        'remark'=>'支付成功'
                    ];
                    db('cash_coupon_list')->data($data_arr)->update($data_arr);

//                    $data_arr1 = [
//                        'uid'=>$member['uid'],
//                        'store_id'=>$coupon['store_id'],
//                        'order_sn'=>$notifyInfo['out_trade_no'],
//                        'pay_time'=>time(),
//                        'pay_status'=>1,
//                        'pay_type'=>1,
//                        'amount'=>$coupon['price'],
//                        'cur_amount'=>$member['user_money'] - $coupon['price'],
//                        'sign'=>2,
//                        'charge_cn'=>'购买代金券',
//                        'addtime'=>time()
//                    ];
//                    db('user_wallet_log')->insert($data_arr1);

                    //会员积分
//                    third_tier_distribution($member['uid'],$coupon['price'],$coupon['store_id'],0,$money=0);          //去掉赠送积分
//                    $where_point_rule['id'] = ['eq',2];
//                    $point_rule = db('sys_point')->where($where_point_rule)->find();
//                    //变更的积分
//                    $point = ceil($coupon['price']/10);
//                    $data_arr2 = [
//                        'uid'=>$member['uid'],
//                        'store_id'=>session('store_id'),
//                        'uidtype'=>1,
//                        'signid'=>2,
//                        'type'=>1,
//                        'point'=>$point,
//                        'curpoint'=>$member['pay_points']+$point,
//                        'type_cn'=>'购买代金券赠送积分',
//                        'remark'=>'购买代金券赠送积分',
//                        'addtime'=>time(),
//                    ];
//                    db('user_point_log')->data($data_arr2)->insert();
//                    $cur_level_point = $member['level_point']+$point;
//                    $cur_pay_point = $member['pay_points']+$point;
//                    $point_rule = db('sys_level')->select();
//                    $level = userLevel($point_rule,$cur_level_point);
//                    $data_arr3 = [
//                        'uid'=>$member['uid'],
//                        'user_money'=>$member['user_money']-$coupon['price'],
//                        'level_point'=>$cur_level_point,
//                        'pay_points'=>$cur_pay_point,
//                    ];
//                    db('user')->data($data_arr3)->update();
                    //支付记录
                    $data_arr4 = [
                        'order_id'=>$coupon['id'],
                        'order_sn'=>$coupon['order_sn'],
                        'order_type'=>1,
                        'uid'=>$coupon['uid'],
                        'pay_type'=>$coupon['pay_type'],
                        'pay_sign'=>3,
                        'amount'=>$coupon['price'],
                        'addtime'=>time(),
                        'store_id'=>$coupon['store_id'],
                        'remark'=>'购买代金券，订单号'.$coupon['order_sn'].'，总价：'.$coupon['price'],
                    ];
                    db('pay_log')->data($data_arr4)->insert();

                    //购买的代金券
                    $cash_coupon = db('store_coupon')->where('id',$coupon['cash_coupon_id'])->find();
                    //创建会员代金券记录
                    $user_coupon_arr = [
                        'store_id'=>$coupon['store_id'],
                        'uid'=>$coupon['uid'],
                        'coupon_id'=>$coupon['cash_coupon_id'],
                        'type'=>2,
                        'cat_id'=>$coupon['cat_id'],
                        'condition'=>$cash_coupon['condition'],
                        'morethan'=>$cash_coupon['morethan'],
                        'reduce'=>$cash_coupon['reduce'],
                        'addtime'=>time(),
                        'price'=>$cash_coupon['price'],
                        'value'=>$cash_coupon['value'],
                        'use_start_time'=>$cash_coupon['use_start_time'],
                        'use_end_time'=>$cash_coupon['use_end_time'],
                        'is_used'=>0,
                        'status'=>1,
                    ];
                    //插入新增的数据
                    db('user_ycard')->data($user_coupon_arr)->insert();

                    //变更门店金额   --  记录数据
                    $store = db('store')->where('id',$coupon['store_id'])->find();
                    $store_credit_log = [
                        'store_id'=>$store['id'],
                        'order_id'=>$coupon['id'],
                        'type'=>1,
                        'credit'=>$cash_coupon['price'],
                        'cur_credit'=>$store['credit']+$cash_coupon['price'],
                        'remark'=>'销售代金券收入',
                        'addtime'=>time(),
                        'order_type'=>2,
                        'order_sn'=>$order['order_sn'],
                        'pay_type'=>2,
                    ];
                    db('store_credit_log')->insert($store_credit_log);
                    $store_credit_arr = [
                        'total_amount'=>$store['total_amount']+$cash_coupon['price'],
                        'credit'=>$store['credit']+$cash_coupon['price']
                    ];
                    db('store')->where('id',$store['id'])->update($store_credit_arr);
                    //变更门店金额 - 更新记录

                    //更新门店线上支付宝收入
                    db('store')->where('id',$coupon['store_id'])->setInc('wx_money',$coupon['price']);

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.order_status")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/my_coupon',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'订单支付成功', "color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$coupon['price'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "keyword3"		=>["value"=>'支付成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"订单支付成功，请到优惠券中心查看", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }else{
                $this->error('支付失败',url('User/index'),1);
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    会员充值回调
     */
    public function recharge(){
        $notifyInfo = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            //处理失败接口
            db('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['charge_cn'=>$notifyInfo['return_msg'],'pay_status'=>-1]);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                $order = Db::name('user_wallet_log')->where("order_sn",$notifyInfo['out_trade_no'])->find();

                if($order['pay_status'] == 0){
                    $member = Db::name('user')->where('uid',$order['uid'])->find();     //会员信息
                    $cur_amount = $order['amount']+$member['user_money'];               //会员当前的金额

                    Db::name('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time(),'cur_amount'=>$cur_amount]);     //更新支付记录

                    Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$order['amount']);        //更新会员余额
                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>$order['pay_type'],'pay_sign'=>2,'amount'=>$order['amount'],'addtime'=>time(),'remark'=>'会员充值，订单号'.$order['order_sn'].'，充值金额：'.$order['amount'],'store_id'=>$order['store_id']]);                  //新增支付记录

                    //会员充值三级分销变更记录
                    recharge_third_distribution($member['uid'],$order['amount']);

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.recharge_msg")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/recharge',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'充值成功提醒', "color"=>"#743A3A"],
                                "accountType" 	    =>["value"=>'充值时间', "color"=>"#743A3A"],
                                "account"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "amount"		=>["value"=>$order['total_amount'], 		"color"=>"#743A3A"],
                                "result"		=>["value"=>'充值成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"您已成功充值，请注意卡内余额变动", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    接受回调的结果
     * @return array
     */
    private function get_notify(){
        $notifyInfo = (array)simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
        return $notifyInfo;
    }


}